<?php

declare(strict_types=1);

namespace app\middleware;

use \app\JsonWebToken;
use \think\facade\Db;
use \app\ErrorResult;

/**
 * Json Web Token中间件处理
 */
class JWTCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取提交的Token
        if (!empty(cookie('Token'))) {
            $token = cookie('Token');
        } elseif (!empty($request->header('Token'))) {
            $token = $request->header('Token');
        } elseif (!empty($request->header('Authorization'))) {
            $token = $request->header('Authorization');
        } else {
            $request->auth = (object)[];
            $request->auth->isLogin = false;
            return $next($request);
        }

        $token = str_replace(" ", "", $token);
        $token = str_replace("Bearer", "", $token);

        $result = JsonWebToken::checkJWT($token);
        if ($result[0]) {
            $user = Db::name('members')->where('uuid', $result[1]->uuid)->find();

            $request->auth = (object)[];
            $request->auth = (object)$user;
            $request->auth->token = $token;
            $request->auth->isLogin = true;

            return $next($request);
        } else {
            return ErrorResult::ErrorResult($result[1], 401);
        }
    }
}
